<template>
  <view class="frequency-selector">
    <u-picker
      :show="showPicker"
      :columns="frequencyColumns"
      @confirm="onConfirm"
      @cancel="onCancel"
      title="选择检查频次"
    />
    <u-input
      v-model="displayText"
      :placeholder="placeholder"
      readonly
      @click="openPicker"
      class="selector-input"
    />
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

// Props定义
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择检查频次'
  }
})

// Emits定义
const emit = defineEmits(['update:modelValue', 'change'])

// 响应式数据
const showPicker = ref(false)

// 检查频次选项
const frequencyOptions = [
  { label: '每小时', value: 'hourly' },
  { label: '每2小时', value: 'every_2_hours' },
  { label: '每日', value: 'daily' }
]

// 选择器数据格式
const frequencyColumns = ref([frequencyOptions])

// 显示文本
const displayText = computed(() => {
  const option = frequencyOptions.find(item => item.value === props.modelValue)
  return option ? option.label : ''
})

// 打开选择器
const openPicker = () => {
  showPicker.value = true
}

// 确认选择
const onConfirm = (event) => {
  console.log('检查频次选择器确认:', event)
  const selectedValue = event.value[0].value
  emit('update:modelValue', selectedValue)
  emit('change', selectedValue)
  showPicker.value = false
}

// 取消选择
const onCancel = () => {
  showPicker.value = false
}

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
  console.log('检查频次外部值变化:', newVal)
})
</script>

<style lang="scss" scoped>
.frequency-selector {
  width: 100%;
}

.selector-input {
  width: 100%;
}
</style>